<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 这里需要根据用户类型判断是否展示：
       （职能部门账号正常展示；
       纪监工委账号专门处理匿名投诉，默认获取到的数据是匿名投诉类型的，因此不需要展示“诉求类型”块） -->
      <el-form-item label="诉求类型" prop="demandsType">
        <el-select v-model="queryParams.demandsType" placeholder="请选择诉求类型" clearable style="width: 240px">
          <el-option label="问题咨询" value="问题咨询" />
          <el-option label="困难求助" value="困难求助" />
          <el-option label="投诉举报" value="投诉举报" />
          <el-option label="服务评价" value="服务评价" />
        </el-select>
      </el-form-item>
      <el-form-item label="诉求状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择诉求状态" clearable style="width: 240px">
          <el-option label="审核不通过" :value="-1" />
          <el-option label="待审核" :value="0" />
          <el-option label="待处理" :value="1" />
          <el-option label="已完成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    

    <el-table v-loading="loading" :data="checkList">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <!-- <el-table-column label="诉求ID" align="center" key="id" prop="id" width="80" /> -->
      <el-table-column label="诉求类型" align="center" key="demandsType" prop="demandsType" width="120" />
      <el-table-column label="标题" align="center" key="title" prop="title" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="内容" align="center" key="content" prop="content" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="图片" align="center" key="images" width="120">
        <template slot-scope="scope">
          <div v-if="getImageList(scope.row.images).length > 0" style="display: inline-block; position: relative;">
            <el-image 
              :src="getImageList(scope.row.images)[0]" 
              :preview-src-list="getImageList(scope.row.images)" 
              style="width: 50px; height: 50px;" 
              fit="cover">
            </el-image>
            <span v-if="getImageList(scope.row.images).length > 1" style="position: absolute; bottom: -2px; right: -2px; background: rgba(0,0,0,0.6); color: white; font-size: 10px; padding: 1px 4px; border-radius: 2px;">
              {{ getImageList(scope.row.images).length }}
            </span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="企业名称" align="center" key="companyName" prop="companyName" :show-overflow-tooltip="true" min-width="180" />
      <el-table-column label="联系人" align="center" key="contact" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.anonymous">匿名</span>
          <span v-else>{{ scope.row.contact || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" key="contactPhone" width="130">
        <template slot-scope="scope">
          <span v-if="scope.row.anonymous">-</span>
          <span v-else>{{ scope.row.contactPhone || '-' }}</span>
        </template>
      </el-table-column>
    
      <el-table-column label="联企人员" align="center" key="memberName" prop="memberName" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.memberName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="诉求状态" align="center" key="status" width="120">
        <template slot-scope="scope">
          <el-tag :type="getAppealStatusType(scope.row.status)">
            {{ getAppealStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" key="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCheck(scope.row)" v-hasPermi="['claim:checkList:check']">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size" @pagination="getList" />

    <!-- 诉求审核对话框 -->
    <el-dialog title="诉求审核" :visible.sync="checkOpen" width="600px" append-to-body>
      <el-form ref="checkForm" :model="checkForm" :rules="checkRules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="企业名称">
              <el-input v-model="checkForm.companyName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="诉求标题">
              <el-input v-model="checkForm.title" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="诉求内容">
              <el-input v-model="checkForm.content" type="textarea" :rows="3" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="诉求状态">
              <el-select v-model="checkForm.status" disabled style="width: 100%;">
                <el-option label="审核不通过" :value="-1" />
                <el-option label="待审核" :value="0" />
                <el-option label="待处理" :value="1" />
                <el-option label="已完成" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核结果" prop="auditResult">
              <el-radio-group v-model="checkForm.auditResult">
                <el-radio :label="1">通过</el-radio>
                <el-radio :label="0">不通过</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="指定部门" prop="branchId">
              <el-select
                v-model="checkForm.branchId"
                placeholder="请选择部门"
                filterable
                clearable
                :loading="branchLoading"
                style="width: 100%;"
                @change="handleBranchChange"
              >
                <el-option
                  v-for="item in branchOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="联企人员" prop="memberId">
              <el-select
                v-model="checkForm.memberId"
                placeholder="请选择联企人员"
                filterable
                clearable
                :loading="memberLoading"
                style="width: 100%;"
                @change="handleMemberChange"
              >
                <el-option
                  v-for="item in memberOptions"
                  :key="item.memberId || item.id"
                  :label="formatMemberLabel(item)"
                  :value="item.memberId || item.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核备注" prop="checkRemark">
              <el-input
                v-model="checkForm.checkRemark"
                type="textarea"
                placeholder="请输入审核备注"
                :rows="3"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCheckForm">确 定</el-button>
        <el-button @click="checkOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="诉求详情" :visible.sync="detailOpen" width="860px" append-to-body>
      <el-descriptions :column="2" border>
        <!-- <el-descriptions-item label="诉求ID">{{ detailForm.id }}</el-descriptions-item> -->
        <el-descriptions-item label="诉求标题">{{ detailForm.title }}</el-descriptions-item>
        <el-descriptions-item label="诉求类型">{{ detailForm.demandsType }}</el-descriptions-item>
        <el-descriptions-item label="企业名称">{{ detailForm.companyName }}</el-descriptions-item>
        <el-descriptions-item label="是否匿名">
          <el-tag :type="detailForm.anonymous ? 'success' : 'info'">
            {{ detailForm.anonymous ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系人" v-if="!detailForm.anonymous">{{ detailForm.contact || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话" v-if="!detailForm.anonymous">{{ detailForm.contactPhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="诉求内容" :span="2">{{ detailForm.content }}</el-descriptions-item>
        <el-descriptions-item label="诉求图片" :span="2">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;" v-if="getImageList(detailForm.images).length > 0">
            <el-image 
              v-for="(img, index) in getImageList(detailForm.images)" 
              :key="index"
              :src="img" 
              :preview-src-list="getImageList(detailForm.images)" 
              style="width: 120px; height: 120px; cursor: pointer;" 
              fit="cover">
            </el-image>
          </div>
        </el-descriptions-item> 
        <el-descriptions-item label="诉求状态">
          <el-tag :type="getAppealStatusType(detailForm.status)">
            {{ getAppealStatusText(detailForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="受理状态">
          <el-tag :type="getAcceptStatusType(detailForm.acceptStatus)">
            {{ getAcceptStatusText(detailForm.acceptStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否结束">
          <el-tag :type="detailForm.isEnd === 1 ? 'success' : 'info'">
            {{ detailForm.isEnd === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联企人员">{{ detailForm.memberName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联企审核时间">{{ (detailForm.memberCheckTime) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核消息">{{ detailForm.checkMessage || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ (detailForm.createTime) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ (detailForm.updateTime) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="企业评价" :span="2">
          <div>
            <span style="margin-right: 10px;">评分：{{ detailForm.companyAppraiseCent || 0 }}分</span>
            <br/>
            <span>评价：{{ detailForm.companyAppraise || '-' }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2" v-if="detailForm.remark">{{ detailForm.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { listAnswer, getAnswer, delAnswer, addAnswer, updateAnswer, processAnswer } from "@/api/claim/checkList"
import { listCheckDemands, listBranch, checkDemands } from "@/api/biz/api"

export default {
  name: "CheckList",
  data() {
    return {
      // 遮罩层
      loading: false, 
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 诉求处置表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示审核弹出层
      checkOpen: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 表单参数
      form: {},
      // 审核表单参数
      checkForm: {},
      // 详情表单参数
      detailForm: {},
      // 部门下拉
      branchOptions: [],
      branchLoading: false,
      // 联企人员下拉
      memberOptions: [],
      memberLoading: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        demandsType: null,
        status: null
      },
      // 列信息
      columns: [
        { key: 0, label: `ID`, visible: true },
        { key: 1, label: `企业名称`, visible: true },
        { key: 2, label: `企业联系人`, visible: true },
        { key: 3, label: `企业联系电话`, visible: true },
        { key: 4, label: `诉求标题`, visible: true },
        { key: 5, label: `诉求内容`, visible: true },
        { key: 6, label: `诉求图片`, visible: true },
        { key: 7, label: `联企人员`, visible: true },
        { key: 8, label: `诉求状态`, visible: true },
        { key: 9, label: `诉求类型`, visible: true },
        { key: 10, label: `创建时间`, visible: true }
      ],

      // 审核表单校验
      checkRules: {
        auditResult: [
          { required: true, message: "请选择审核结果", trigger: "change" }
        ],
        branchId: [
          { required: true, message: "请选择部门", trigger: "change" }
        ],
        checkRemark: [
          { required: false, message: "请输入审核备注", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.fetchBranchOptions()
    // this.fetchMemberOptions()
  },
  methods: {
    /** 查询诉求审核列表 */
    getList() {
      this.loading = true
      // 构建符合 API 要求的查询参数
      const params = {
        current: (this.queryParams.current && this.queryParams.current > 0) ? this.queryParams.current - 1 : 0, // API 使用从 0 开始的索引
        size: this.queryParams.size || 10
      }
      console.log('this.queryParams.demandsType === ',this.queryParams.demandsType)

      if (this.queryParams.demandsType !== null) {
        params.demandsType = this.queryParams.demandsType
      }

      // 只有当 status 有值时才添加
      if (this.queryParams.status !== null) {
        params.status = this.queryParams.status
      }

      listCheckDemands(params).then(response => {
        console.log('诉求部门列表 ：',response);
        
        this.checkList = response.data?.records || []
        this.total = response.data?.total || 0
        this.loading = false
      })
    },

    // 获取部门下拉
    fetchBranchOptions() {
      this.branchLoading = true
      listBranch()
        .then(response => {
          this.branchOptions = response.data || []
        })
        .catch(error => {
          console.error('获取部门列表失败', error)
        })
        .finally(() => {
          this.branchLoading = false
        })
    },
    // 获取联企人员下拉
    // fetchMemberOptions() {
    //   this.memberLoading = true
    //   const params = {
    //     current: 1,
    //     size: 200
    //   }
    //   pageBranchMeb(params)
    //     .then(response => {
    //       this.memberOptions = response.data?.records || []
    //     })
    //     .catch(error => {
    //       console.error('获取联企人员失败', error)
    //     })
    //     .finally(() => {
    //       this.memberLoading = false
    //     })
    // },
    // 下拉联动
    handleBranchChange(value) {
      // 部门选择变化处理（如需要可在此添加逻辑）
    },
    // handleMemberChange(value) {
    //   const target = this.memberOptions.find(item => item.memberId === value || item.id === value)
    //   this.checkForm.memberName = target ? (target.memberLinkName || target.memberName || target.name) : ''
    // },
    // formatMemberLabel(member) {
    //   if (!member) {
    //     return ''
    //   }
    //   const name = member.memberLinkName || member.memberName || member.name || '-'
    //   const phone = member.memberLinkPhone || member.phone || ''
    //   const branch = member.branchName || member.deptName || ''
    //   const displayBranch = branch ? `（${branch}）` : ''
    //   return phone ? `${name}${displayBranch} - ${phone}` : `${name}${displayBranch}`
    // },
 
    
    // 审核表单重置
    resetCheckForm() {
      this.checkForm = {
        demandsId: undefined,
        companyName: undefined,
        title: undefined,
        content: undefined,
        status: undefined,
        auditResult: undefined,
        branchId: undefined,
        checkRemark: ""
      }
      this.resetForm("checkForm")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    }, 
 
    /** 审核按钮操作 */
    handleCheck(row) {
      this.resetCheckForm()
      this.checkForm = {
        demandsId: row.demandsId || row.id,
        companyName: row.companyName,
        title: row.title,
        content: row.content,
        status: row.status,
        auditResult: undefined,
        branchId: row.branchId,
        checkRemark: row.checkRemark || ""
      }
      this.checkOpen = true
    },
    /** 查看详情操作 */
    handleView(row) {
      this.detailForm = { ...row }
      this.detailOpen = true
    }, 
    /** 提交审核表单 */
    submitCheckForm: function() {
      // 注意：这里是否需要区分登录账号（职能部门和纪监工委），然后区分调用接口？
      
      this.$refs["checkForm"].validate(valid => {
        if (valid) {
          const payload = {
            demandsId: this.checkForm.demandsId,
            op: this.checkForm.auditResult,
            departs: this.checkForm.branchId ? [this.checkForm.branchId] : [],
            remark: this.checkForm.checkRemark || ""
          }
          checkDemands(payload)
            .then(() => {
              this.$modal.msgSuccess("审核成功")
              this.checkOpen = false
              this.getList()
            })
            .catch(error => {
              console.error('审核诉求失败', error)
            })
        }
      })
    },
    
    // 获取处置状态文本（保留用于其他功能）
    getHandlingStatusText(status) {
      const statusMap = {
        'not_accepted': '未受理',
        'processing': '处理中',
        'completed': '已完成'
      }
      return statusMap[status] || status
    },
    // 获取处置状态类型（保留用于其他功能）
    getHandlingStatusType(status) {
      const typeMap = {
        'not_accepted': 'warning',
        'processing': 'primary',
        'completed': 'success'
      }
      return typeMap[status] || ''
    },
    // 获取诉求状态文本（根据数字状态）
    getAppealStatusText(status) {
      // 处理数字状态值：-1, 0, 1, 2
      const statusMap = {
        '-1': '审核不通过',
        '0': '待审核',
        '1': '待处理',
        '2': '已完成'
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return statusMap[statusKey] || (status !== null && status !== undefined ? String(status) : '-')
    },
    // 获取诉求状态类型（根据数字状态）
    getAppealStatusType(status) {
      // 处理数字状态值：-1, 0, 1, 2
      const typeMap = {
        '-1': 'danger',
        '0': 'warning',
        '1': 'primary',
        '2': 'success'
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return typeMap[statusKey] || ''
    },
    // 解析图片字符串为数组
    getImageList(images) {
      if (!images) {
        return []
      }
      // 如果已经是数组，直接返回并过滤空值
      if (Array.isArray(images)) {
        return images.filter(img => img && (typeof img === 'string' ? img.length > 0 : true))
      }
      // 如果是字符串，按逗号分割并过滤空值
      if (typeof images === 'string') {
        return images.split(',').map(img => img.trim()).filter(img => img.length > 0)
      }
      return []
    },
    // 获取受理状态文本
    getAcceptStatusText(status) {
      const statusMap = {
        '0': '待受理',
        '1': '已受理',
        '2': '已拒绝'
      }
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return statusMap[statusKey] || (status !== null && status !== undefined ? String(status) : '-')
    },
    // 获取受理状态类型
    getAcceptStatusType(status) {
      const typeMap = {
        '0': 'warning',
        '1': 'success',
        '2': 'danger'
      }
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return typeMap[statusKey] || ''
    }
  }
}
</script>
